package com.bluexmicro.example.page.pick.peripheral.condition

import android.Manifest
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.widget.Toast
import androidx.compose.runtime.mutableStateOf
import androidx.core.app.ActivityCompat
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bluexmicro.android.coroutineble.model.BleFactor
import com.bluexmicro.android.coroutineble.model.bleFactorMonitor
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.PermissionState
import com.google.accompanist.permissions.isGranted
import com.google.accompanist.permissions.shouldShowRationale
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

enum class ConditionState {
    IDLE, READY, NOT_READY
}

class ConditionViewModel : ViewModel() {

    var items = mutableStateOf<List<ConditionItemModel>>(emptyList())
    var ready = mutableStateOf(ConditionState.IDLE)

    private var job: Job? = null

    @OptIn(ExperimentalPermissionsApi::class)
    fun onResume(
        context: Context,
        locationPermissionState: PermissionState,
        scanPermissionState: PermissionState?,
        connectPermissionState: PermissionState?
    ) {
        job?.takeIf { it.isActive }?.apply { cancel() }
        job = viewModelScope.launch {
            context.bleFactorMonitor().collect {
                ready.value =
                    if (it.scanAndConnectReady()) ConditionState.READY else ConditionState.NOT_READY
                it.updateItems(locationPermissionState, scanPermissionState, connectPermissionState)
            }
        }
    }

    fun onStop() {
        job?.takeIf { it.isActive }?.apply { cancel() }
    }

    @OptIn(ExperimentalPermissionsApi::class)
    private fun BleFactor.updateItems(
        locationPermissionState: PermissionState,
        scanPermissionState: PermissionState?,
        connectPermissionState: PermissionState?
    ) {
        val connectBean = ConditionItemModel(
            if (bluetoothConnectPermission) "「连接蓝牙」已授权" else "「连接蓝牙」未授权",
            if (bluetoothConnectPermission) "已授权" else "去授权",
            bluetoothConnectPermission.not()
        ) {
            connectPermissionState?.apply {
                if (status.shouldShowRationale) {
                    it.manualGrant()
                } else {
                    launchPermissionRequest()
                }
            }
        }

        val scanBean = ConditionItemModel(
            if (bluetoothScanPermission) "「扫描蓝牙」已授权" else "「扫描蓝牙」未授权",
            if (bluetoothScanPermission) "已授权" else "去授权",
            bluetoothScanPermission.not()
        ) {
            scanPermissionState?.apply {
                if (status.shouldShowRationale) {
                    it.manualGrant()
                } else {
                    launchPermissionRequest()
                }
            }
        }

        val bluetoothBean = ConditionItemModel(
            if (bluetoothEnable) "「蓝牙」已打开" else "「蓝牙」未打开",
            if (bluetoothEnable) "已就绪" else "去打开「蓝牙」",
            bluetoothEnable.not()
        ) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S || ActivityCompat.checkSelfPermission(
                    it,
                    Manifest.permission.BLUETOOTH_CONNECT
                ) == PackageManager.PERMISSION_GRANTED
            ) {
                val manager = it.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager?
                manager?.adapter?.enable()
            } else {
                Toast.makeText(it, "请先授予「连接蓝牙」的权限", Toast.LENGTH_LONG)
                    .show()
            }
        }

        val locationBean = ConditionItemModel(
            if (locationEnable) "「位置信息」已打开" else "「位置信息」未打开",
            if (locationEnable) "已就绪" else "去打开「位置信息」",
            locationEnable.not()
        ) {
            val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
            it.startActivity(intent)
        }

        val locationPermissionBean = ConditionItemModel(
            if (locationPermission) "「位置信息」已授权" else "「位置信息」未授权",
            if (locationPermission) "已授权" else "去授权",
            locationPermission.not()
        ) {
            if (locationPermissionState.status.shouldShowRationale) {
                it.manualGrant()
            } else {
                locationPermissionState.launchPermissionRequest()
            }
        }
        items.value =
            listOf(bluetoothBean, scanBean, connectBean, locationBean, locationPermissionBean)
    }
}

data class ConditionItemModel(
    val content: String,
    val btnContent: String,
    val enable: Boolean,
    val action: (Context) -> Unit
)

/**
 * 跳转到设置页面
 */
fun Context.manualGrant() {
    val intent = Intent()
    intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
    intent.data = Uri.parse("package:$packageName")
    startActivity(intent)
}